package com.lccviolet;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LiChaochao
 * @Date 2021/9/10 19:34
 * @Description ProdConsumer_TraditionDemo 多线程需求的传统写法
 * 需求：
 *      初始值为0的变量，两个线程交替操作，一个+1，一个-1，来5轮
 *
 * 技巧：
 *      线程  操作  资源类；
 *      判断  干活  再通知;
 *      防止虚假唤醒
 *
 * 注意：
 *      多线程环境下判断用while，不用if，防止虚假唤醒
 */
public class ProdConsumer_TraditionDemo {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareData.add();
            }
        }, "t1").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareData.sub();
            }
        }, "t2").start();
    }
}

class ShareData {
    private int data = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void add() {
        lock.lock();
        try {
            while (data == 1) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(data++);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void sub() {
        lock.lock();
        try {
            while (data == 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(data--);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
